package file;

import cn.hutool.core.util.StrUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;

public class FileUtil {

    /**
     * 创建文件夹目录
     * @param dirPath 路径目录，如：C:\Users\Alex\Desktop\临时\cipos-work
     */
    public static void createDir(String dirPath) {
        Path path = Paths.get(dirPath);
        if (Files.exists(path)) {
            if (Files.isDirectory(path)) {
                return;
            } else {
                throw new RuntimeException("存在同名文件！");
            }
        }
        try {
            Files.createDirectories(path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 写出到文件
     * @param filePath 文件路径，如：C:\Users\Alex\Desktop\临时\cipos-work.sql
     * @param contentList 内容
     */
    public static void write(String filePath, List<String> contentList) {
        Path path = Paths.get(filePath);
        try (BufferedWriter writer = Files.exists(path) ? Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)
                : Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.CREATE)) {
            for (String line : contentList) {
                writer.write(line);
                writer.newLine(); // 写入新行
            }
            System.out.println("内容已成功添加到文件: " + filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void write(String filePath,String... content) {
        write(filePath, Arrays.asList(content));
    }


    public static void main(String[] args) {
        // FileUtil.createDir("C:\\Users\\Alex\\Desktop\\临时\\cipos-work\\xxx");

        // String scriptPath = "C:\\Users\\Alex\\Desktop\\临时\\cipos-work\\xxx.sql";
        // List<String> contentList = new ArrayList<>();
        // contentList.add("这是第一行;");
        // contentList.add("这是第二行;");
        // contentList.add("这是第三行;");
        // FileUtil.write(scriptPath, contentList);

        String dir = "C:\\Users\\Alex\\Desktop\\临时\\cipos-work\\";
        final String s = StrUtil.appendIfMissing(dir, File.separator);
        System.out.println(StrUtil.appendIfMissing(s, "xxx"));
    }
}
